# 导入视图的异常处理类
from rest_framework.views import exception_handler
# 导入响应
from rest_framework.response import Response
# 导入数据库的错误
from rest_framework.exceptions import ValidationError
# 导入0 不能当除数的异常
from django.core.exceptions import ZeroDivisionError
from django.db import DatabaseError

# 导入日志处理函数
import logging
logger = logging.getLogger('django')
# 定义异常处理类
def custom_exception_handler(exc, context):
    response = exception_handler(exc, context)

    if response is None:
        view = context['view']
        #判读是数据库的错误
        if isinstance(exc, DatabaseError):
            # 数据库异常
            logger.error('[%s] %s' % (view, exc))
            response = Response({'message': '服务器内部错误'}, status=500)
        if isinstance(exc, ZeroDivisionError):
            response = Response({'message': '0不能当成除数'}, status=500)

    return response